import React, { Component } from 'react';
import { Form, Input, Modal, Button, InputNumber, Select, DatePicker, Icon, Row, Col} from 'antd';
import moment from 'moment';
const { TextArea } = Input;
const FormItem = Form.Item;
const Option = Select.Option;

import WithModal from '@/hocs/WithModal'

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

@Form.create()
@WithModal({pathname: 'leave/fetch'})
export default class FormModal extends Component {

  constructor(props) {
    super(props);
    this.state = {
      leaveType: [],
      approver:[],
    }
  }

  //提交表单
  onSubmit = () => {
    this.props.form.validateFields((err, params) => {
      if (!err) {
        const p = {
          ...params,
          leaveBeginDate:params['leaveBeginDate'].format('YYYY-MM-DD'),
          leaveEndDate:params['leaveEndDate'].format('YYYY-MM-DD')
        }
        this.props.okHandler(p, '确定后，将自动发起请假流程，请问继续吗？');
      }
    })
  }

  //显示弹出框
  showModelHandler = () => {
    const { dispatch, record } = this.props;
    const _this = this;
    dispatch({type: 'app/fetchDics', payload: {code: 'leaveType'}}).then(data => {
      if(data) {
        const { data:{leaveType} } = data;
        _this.setState({leaveType});
        _this.props.showModelHandler();
      }
    })

    if(record.id && record.leaveDays) {
      this.fetchApprover(record.leaveDays);
    } 
  }

  /**
   * 组装下拉选择
   */
  packageLeaveTypeSelect= (datas) => datas.map(item => {
    return <Option key = {item.value}>{item.name}</Option>
  })

  /**
   * 组装下一步审批人下拉选择
   */
  packageNextSelect= (datas) => datas.map(item => {
    return <Option key = {item.id}>{item.name}</Option>
  })

  //获取审批人
  fetchApprover = (leaveDays) => {
    const _this = this;
    //获取审批人前清空选项
    this.props.form.resetFields(['nextUserId'])
    if(leaveDays > 0) {
      this.props.dispatch({type: 'app/fetchApprover', payload: {type: '1', leaveDays}}).then(data => {
        if(data) {
          _this.setState({
            approver:data.data
          });
        }
      })
    } else {
      Message.warning('请假天数必须大于等于1天')
    }
  }

  //请假开始改变事件
  onStartChange = (value, dateString) => {
    const { form, dispatch } = this.props;
    const { leaveEndDate } = form.getFieldsValue(['leaveEndDate']);
    if(leaveEndDate) {
      const leaveDays = moment(leaveEndDate - value).format('D');
      form.setFieldsValue({
        leaveDays
      });
      //获取审批人
      this.fetchApprover(leaveDays);
    }
  }

  //请假结束改变事件
  onEndChange = (value, dateString) => {
    const { form } = this.props;
    const { leaveBeginDate } = form.getFieldsValue(['leaveBeginDate']);
    if(leaveBeginDate) {
      const leaveDays = moment(value - leaveBeginDate).format('D');
      form.setFieldsValue({
        leaveDays
      });
      //获取审批人
      this.fetchApprover(leaveDays);
    }
  }

  //限制日期选择
  disabledStartDate = (startValue) => {
    const { leaveEndDate } = this.props.form.getFieldsValue(['leaveEndDate']);
    if (!startValue || !leaveEndDate) {
      return false;
    }
    return startValue.valueOf() > leaveEndDate.valueOf();
  }
  //限制日期选择
  disabledEndDate = (endValue) => {
    const { leaveBeginDate } = this.props.form.getFieldsValue(['leaveBeginDate']);;
    if (!endValue || !leaveBeginDate) {
      return false;
    }
    return endValue.valueOf() <= leaveBeginDate.valueOf();
  }
  render() {
    const { children, title, loading, record, visible, hideModelHandler } = this.props;
    const { getFieldDecorator } = this.props.form;

    return (
      <span>
        <span onClick={this.showModelHandler}>
          { children }
        </span>
        <Modal
          title={title}
          visible={visible}
          width={560}
          maskClosable={false}
          onCancel={hideModelHandler}
          footer={[
          <Button key="back" type="ghost" size="large" onClick={hideModelHandler}>取消</Button>,
          <Button key="submit" type="primary" size="large" disabled={loading} loading={loading} onClick={this.onSubmit}>
            {loading ? '处理中...' : '确定'}
          </Button>,
        ]}
        >
          <Form layout='horizontal' onSubmit={this.onSubmit}>
            <FormItem
              {...formItemLayout}
              label="请假类型"
            >
            {getFieldDecorator('leaveType', {
              rules: [
                  { required: true, message: '请选择请假类型' }
                ],
                initialValue: record['leaveType'] || null
              })(
                <Select
                  placeholder="请选择请假类型"
                >
                  {this.packageLeaveTypeSelect(this.state.leaveType)}
                </Select>
            )}
            </FormItem>
            <FormItem
              label="请假周期"
              {...formItemLayout}
            >
              <Col span={11}>
                <FormItem>
                  {getFieldDecorator('leaveBeginDate', {
                    rules: [
                      {required: true, message: '请选择请假开始日期'}
                    ],
                    initialValue: record['leaveBeginDate'] && moment(record['leaveBeginDate'], 'YYYY-MM-DD HH:mm:ss')
                  })(
                    <DatePicker onChange={this.onStartChange} disabledDate={this.disabledStartDate}/>
                  )}
                </FormItem>
              </Col>
              <Col span={2}>
                <span style={{ display: 'inline-block', width: '100%', textAlign: 'center' }}>
                  -
                </span>
              </Col>
              <Col span={11}>
                <FormItem>
                  {getFieldDecorator('leaveEndDate', {
                    rules: [
                      {required: true, message: '请选择请假结束日期'}
                    ],
                    initialValue: record['leaveEndDate'] && moment(record['leaveEndDate'], 'YYYY-MM-DD HH:mm:ss')
                  })(
                    <DatePicker onChange={this.onEndChange} disabledDate={this.disabledEndDate}/>
                  )}
                </FormItem>
              </Col>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="请假天数"
              help="由请假周期自动生成"
            >
              {getFieldDecorator('leaveDays', {
                initialValue: record['leaveDays'] || 0
              })(
                <InputNumber min={0} readOnly={true}/>
              )}
              <span className="ant-form-text"> 天</span>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="请假审批人"
            >
            {getFieldDecorator('nextUserId', {
              rules: [
                  { required: true, message: '请选择审批人' }
                ],
                initialValue: record['nextUserId'] || null
              })(
                <Select
                  placeholder="请选择审批人"
                  notFoundContent="请先选择请假周期"
                >
                  {this.packageNextSelect(this.state.approver)}
                </Select>
            )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="请假事由"
            >
              {getFieldDecorator('leaveReason', {
                rules: [
                   { required: true, message: '请输入请假事由' },
                   { max: 250, message: '不能超过250位字符' }
                 ],
                 initialValue: record['leaveReason'] || ''
               })(
                <TextArea rows={4} placeholder="请输入请假事由" />
              )}
            </FormItem>
          </Form>
        </Modal>
      </span>
    );
  }
}
